<?php

namespace app\index\controller;

use app\index\model\FirClassification;
use app\index\model\SecClassification;
use think\Controller;

class ClassificationCtl extends Controller
{
    /*
     * 获取一级分类，结果带有相应二级分类
     */
    public function getFirCla()
    {
        $res['data'] = FirClassification::with('sec')->select();
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 添加一级分类
     */
    public function addFirCla()
    {
        FirClassification::create([
            'name' => input('name')
        ]);
        return json(['msg' => '添加成功', 'code' => 20000]);
    }

    /*
     * 删除一级分类，同时删除相应二级分类
     */
    public function delFirCla()
    {
        $fir = FirClassification::get(input('id'), 'sec');
        $fir->together('sec')->delete();
        return json(['msg' => '删除成功', 'code' => 20000]);
    }

    /*
     * 更新一级分类
     */
    public function updFirCla()
    {
        FirClassification::update([
            'id' => input('id'),
            'name' => input('name')
        ]);
        return json(['msg' => '修改成功！', 'code' => 20000]);
    }

    /*
     * 获取所有二级分类
     */
    public function getSecCla()
    {
        $res['data'] = SecClassification::field('id,pid,name')->select();
        $res['code'] = 20000;
        return json($res);
    }

    /*
     * 新增二级分类
     */
    public function addSecCla()
    {
        SecClassification::create([
            'pid' => input('pid'),
            'name' => input('name')
        ]);
        return json(['msg' => '添加成功！', 'code' => 20000]);
    }

    /*
     * 删除二级分类
     */
    public function delSecCla()
    {
        SecClassification::destroy(input('id'));
        return json(['msg' => '删除成功！', 'code' => 20000]);
    }

    /*
     * 更新二级分类
     */
    public function updSecCla()
    {
        SecClassification::update([
            'id' => input('id'),
            'pid' => input('pid'),
            'name' => input('name')
        ]);
        return json(['msg' => '修改成功！', 'code' => 20000]);
    }
}